import os
import json
from db.userDBManager import UserDBManager
from .project import Project
from utils.randomUtils import generate_random_string
class User:
    def __init__(self, user_id, user_db_manager:UserDBManager):
        self.user_id = user_id  
        self.user_db_manager = user_db_manager 
        pro_raw = user_db_manager.get_user_projects(user_id)
        self.user_info = user_db_manager.get_user_login_info(user_id)
        self.editingProjects = pro_raw
        self.runningProjects = {}

    # 用户 将Project 加入到EditingProjects中
    def addEditingProject(self, project_id, content):
        self.editingProjects[project_id] = content
        return self.editingProjects[project_id]

    def stopProject(self,project_id):
        if (project_id not in self.runningProjects): return
        pro = self.runningProjects[project_id]
        pro.stop()

    def deployProject(self, project_id,project_name, content):
        project =  ProjectManager.instance.addProject(generate_random_string(self.user_id, project_id), project_id, project_name, self)
        project.deployProject(content)
        self.runningProjects[project_id] = project

    def getEditingProject(self, project_id)->Project:
        if project_id not in self.editingProjects: 
            return None
        return self.editingProjects.get(project_id)
    
    def getEditingProjects(self)->list[Project]:
        return list(self.editingProjects.values())
    
    def saveUserProject(self, projectID, projectContent)->bool:
        self.editingProjects[projectID] = projectContent
        pros = self.user_db_manager.get_user_projects(self.user_id)
        pros[projectID] = projectContent
        self.user_db_manager.save_user_projects(self.user_id, pros)
        return True

    def getEditingProjects(self):
        return self.editingProjects
    def getRunningProjects(self):
        return self.runningProjects
    def getUserInfo(self):
        return self.user_info
    def updateUserInfo(self, new_info):
        self.user_info.update(new_info)
        self.user_db_manager.update_user_info(self.user_id, self.user_info)
        return True

class UserManager:
    def __init__(self, user_db_manager: UserDBManager):
        self.users = {}
        self.users_db_manager = user_db_manager

    def addUser(self, user_id):
        self.users[user_id] = User(user_id, self.users_db_manager)
        return self.users[user_id]

    def getUser(self, user_id)->User:
        if user_id not in self.users: 
            return None
        return self.users.get(user_id)

    def removeUser(self, user_id):
        if user_id in self.users:
            del self.users[user_id]
            return True
        return False


class ProjectManager: #管理当前正在运行的项目
    instance = None
    app = None
    def __init__(self, app):
        self.randomKeyToProject = {}
        ProjectManager.instance = self
        ProjectManager.app = app

    def addProject(self, random_key, project_id, project_name, user:User):
        self.randomKeyToProject[random_key] = Project(project_id, random_key, project_name, user)
        return self.randomKeyToProject[random_key]

    def delete_project(self, project_id, requesting_user_id):

        try:
            # 1. 检查项目是否存在
            project = self.get_project_by_id(project_id)
            if not project:
                return False, "项目不存在"

            # 2. 权限检查（只有项目创建者可以删除）
            if project.user.userID != requesting_user_id:
                return False, "无权删除此项目"

            # 3. 从内存中删除项目
            del self.randomKeyToProject[project.random_key]

            # 4. 删除用户项目文件中的项目记录
            user_file_path = f'./db/data/users/{requesting_user_id}.json'
            print(f"尝试删除的项目文件路径: {os.path.abspath(user_file_path)}")

            if not os.path.exists(user_file_path):
                return False, "用户项目文件不存在"

            # 读取用户项目数据
            with open(user_file_path, 'r', encoding='utf-8') as f:
                user_data = json.load(f)

            # 检查项目是否存在
            if 'user_projects' not in user_data or project_id not in user_data['user_projects']:
                return False, "项目不存在于用户文件中"

            # 删除项目记录
            del user_data['user_projects'][project_id]

            # 保存更新后的用户项目文件
            with open(user_file_path, 'w', encoding='utf-8') as f:
                json.dump(user_data, f, ensure_ascii=False, indent=2)

            # 5. （可选）从主用户数据库更新项目列表
            main_db_path = './db/data/users/users_data.json'
            if os.path.exists(main_db_path):
                with open(main_db_path, 'r', encoding='utf-8') as f:
                    main_db = json.load(f)

                if requesting_user_id in main_db and 'user_projects' in main_db[requesting_user_id]:
                    if project_id in main_db[requesting_user_id]['user_projects']:
                        del main_db[requesting_user_id]['user_projects'][project_id]

                        with open(main_db_path, 'w', encoding='utf-8') as f:
                            json.dump(main_db, f, ensure_ascii=False, indent=2)

            return True, "删除成功"

        except Exception as e:
            print(f"Error deleting project: {e}")
            return False, f"删除失败: {str(e)}"

    def get_project_by_id(self, project_id):
        """根据项目ID获取项目"""
        for proj in self.randomKeyToProject.values():
            if proj.project_id == project_id:
                return proj
        return None